package middleware

import (
	"GoGin/common"
	"GoGin/model"
	"GoGin/response"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// 认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenString := c.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") { // 错误格式的token
			response.Response(c, http.StatusUnprocessableEntity, 401, nil, "权限不足.")
			c.Abort() // 抛弃请求
			return
		}
		// 提取token的有效部分
		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString) // 解析tokenString

		if err != nil || !token.Valid {
			response.Response(c, http.StatusUnprocessableEntity, 401, nil, "权限不足.")
			c.Abort() // 抛弃请求
			return
		}

		// 通过验证,获取claims中的userID
		userID := claims.UserID
		db := common.InitDB()
		var user model.User
		db.First(&user, userID)

		if user.ID == 0 {
			response.Response(c, http.StatusUnprocessableEntity, 401, nil, "权限不足.")
			c.Abort() // 抛弃请求
			return
		}

		// 如果用户存在 将User信息写入上下文
		c.Set("user", user)
		c.Next()
	}
}
